from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django.http import HttpResponse
# Create your views here.
from ihome.libs.captcha.captcha import captcha
from django.http import JsonResponse
import logging ,random,json
logger = logging.getLogger('django')


from ihome.libs.yuntongxun.ccp_sms import CCP



class ImageCodeView(View):

    def get(self,request):
        cur = request.GET.get('cur')
        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % cur,300,text)
        return HttpResponse(image,
                            content_type='image/jpg')

class SMSCodeView(View):
    def post(self,request):
        dict = json.loads(request.body.decode())

        mobile = dict.get('mobile')
        id = dict.get('id')
        text = dict.get('text')
        if not all([mobile,text,id]):
            return JsonResponse({'errno': '4004',
                                 'errmsg':'缺少必传参数'})
        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s' % id)
        if image_code_server is None :
            return JsonResponse({'errno': '4004',
                                 'errmsg': '图片验证码过期'})
        try:
            redis_conn.delete('img_%s' % id)
        except Exception as e:
            logger.info(e)
        image_code_server = image_code_server.decode()
        if text.lower() != image_code_server.lower():
            return JsonResponse({'errno': '4004',
                                 'errmsg': '输入的图形码出错'})
        sms_code = '%06d' % random.randint(0,999999)
        logger.info(sms_code)
        redis_conn.setex('sms%s'% mobile,300,sms_code)
        CCP().send_template_sms('mobile', ['sms_code', 5], 1)

        return JsonResponse({'errno': '0',
                             'errmsg': '发送成功'})





